package core.webserver.core;

import core.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            HttpRequest request = new HttpRequest(socket);
            String path = request.getUri();
            File file = new File("./webapps"+path);
            OutputStream out = socket.getOutputStream();
            String line = "HTTP/1.1 200 OK";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);
            out.write(13);
            out.write(10);
            FileInputStream fis = new FileInputStream(file);
            data = new byte[1024*10];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
            System.out.println("响应发送完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}